package com.chinaway.dsp.test;

import java.io.BufferedReader;
import java.io.FileReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.chinaway.dsp.action.CallDspInterfaceAction;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.wb.swt.SWTResourceManager;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.DateTime;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import com.chinaway.dsp.action.BackAction;
import com.chinaway.dsp.conn.TestConn;
import com.chinaway.dsp.util.AccStatus;
import com.chinaway.dsp.util.CallHtml;
import com.chinaway.dsp.util.CountBean;
import com.chinaway.dsp.util.LngLatVerifyListener;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.graphics.Point;

public class MessageSend {
	private static Text dsp_ip_text;
	private static Text dsp_port_text;
	private static Text imei_text;
	private static Text import_path_text;
	public static String tracePath="";
	private static Table csv_table;
	private static Text log_info_text;
	private static TestConn tc=null;
	private static Text lng_text;
	private static Text lat_text;
	private static Text speed_text;
	private static Text course_text;
	private static Text displaytime_text;
	private static SimpleDateFormat msgsendtime;
	private static SimpleDateFormat nowtime;
	private static String displaytime;
	private static int acc_status=0;
//	private static CCombo device_combo;
	public static int device_type_int=-1;
	public static boolean connectFlag=false;
	private static Button conn_btn;
	private static Button acc_status_btn;
	private static final String[] device_type = { "Smart", "部标"};
	private static final String[] event_type = { "超速","急刹车","急减速","离线","疲劳驾驶","未登签"};
	private static Spinner send_iterationtime_spinner;
	private static Spinner send_totaltime_spinner;
//	static Display display;
	public static List<String> dataList = new ArrayList<String>();
	public static List l;
	private static Button settime_btn;
	final static CountBean cb=new CountBean();
	static BackAction ba=new BackAction();
	static Thread actionThread;
	static Button send_stop_btn;
	static Button send_btn;
	static Spinner send_interval_spinner;
	static Button send_iteration_btn;
	static int opencount=0;
	static int reconnect_count=0;
	private static AccStatus as=new AccStatus();
	final static String testDspApi="http://test.dsp.chinawayltd.com/router/rest";
	final static String demoDspApi="http://demo.dsp.chinawayltd.com/router/rest";
	final static String productDspApi="http://api.huoyunren.com/router/rest";
	final static String allowDeviceList[]={"106014002020068","107015090000007","106014100045724","106014100111539","106014100109953"};
	final static String smartServerPortList[]={"16531","16532","9001"};
	final static String gnnsServerPortList[]={"2906","2916","2926","2946","906"};
	final static String volvoServerPortList[]={"2904","2914"};
	static boolean allowDeviceConnect=false;
	private static Text device_type_text;
	final static String SMART="SMART";
	final static String GNNS="部标";
	final static String VOLVO="VOLVO";
	
	
	public MessageSend(Display display,final Shell shell){
		ba.setMainUI(display);
		ba.setCountBean(cb);
		ba.setAccStatus(as);
//		final Shell shell = new Shell(display,SWT.CLOSE);
		shell.setMinimumSize(new Point(76, 75));
		shell.setSize(1290, 505);
		shell.setText("报文发送工具");
        shell.setImage(SWTResourceManager.getImage(MessageSend.class, "/res/g7.png"));
        
		TabFolder tabFolder = new TabFolder(shell, SWT.NONE);
		tabFolder.setBounds(10, 10, 1254, 460);
		
		TabItem mini_tabItem = new TabItem(tabFolder, SWT.NONE);
		mini_tabItem.setText("精简报文");
		
		final Composite mini_composite = new Composite(tabFolder, SWT.NONE);
		mini_composite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_BACKGROUND));
		mini_tabItem.setControl(mini_composite);
		
		String htmlPath=Thread.currentThread().getContextClassLoader().getResource("res/getRoute.html").getPath();
		final Browser browser = new Browser(mini_composite, SWT.NONE);
		browser.setBounds(676, 33, 560, 382);
		System.out.println(htmlPath);
//		browser.setUrl(htmlPath.substring(6,htmlPath.indexOf("sendtrace"))+"getRoute.html");
		browser.setUrl(htmlPath.substring(1,htmlPath.length()));
		final CallHtml ch=new CallHtml(browser,"callhtml",ba);
		l=ch.getRouteList();
//		ba.setBrowser(browser);
		log_info_text = new Text(mini_composite, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
		log_info_text.setBounds(396, 267, 274, 148);
		tc=new TestConn(log_info_text);
		tc.setDisplay(display);
		tc.setShell(shell);
		tc.setCountBean(cb);
		tc.setBackAction(ba);
		tc.setAccStatus(as);
		Label dsp_ip_lbl = new Label(mini_composite, SWT.NONE);
		dsp_ip_lbl.setBounds(10, 25, 50, 17);
		dsp_ip_lbl.setText("DSP IP：");
		
		dsp_ip_text = new Text(mini_composite, SWT.BORDER);
		dsp_ip_text.setBounds(62, 22, 107, 23);
		dsp_ip_text.setTextLimit(15);
		Label dsp_port_lbl = new Label(mini_composite, SWT.NONE);
		dsp_port_lbl.setBounds(175, 25, 61, 17);
		dsp_port_lbl.setText("DSP 端口：");
		
		dsp_port_text = new Text(mini_composite, SWT.BORDER);
		dsp_port_text.setBounds(237, 22, 50, 23);
		dsp_port_text.setTextLimit(5);
		dsp_port_text.addVerifyListener(new VerifyListener() { 
			   public void verifyText(VerifyEvent e) {   
			    // 几种情况，输入控制键，输入中文，输入字符，输入数字   
			    // 正整数验证   
			    Pattern pattern = Pattern.compile("[0-9]\\d*");   
			    Matcher matcher = pattern.matcher(e.text);   
			    if (matcher.matches()) // 处理数字   
			     e.doit = true;   
			    else if (e.text.length() > 0) // 有字符情况,包含中文、空格   
			     e.doit = false;   
			    else  
			     // 控制键   
			     e.doit = true;   
			   }   
			  });
		imei_text = new Text(mini_composite, SWT.BORDER);
		imei_text.setBounds(62, 65, 118, 23);
		imei_text.setTextLimit(15);
		imei_text.addVerifyListener(new VerifyListener() {   
			   public void verifyText(VerifyEvent e) {   
				    // 几种情况，输入控制键，输入中文，输入字符，输入数字   
				    // 正整数验证   
				    Pattern pattern = Pattern.compile("[0-9]\\d*");   
				    Matcher matcher = pattern.matcher(e.text);   
				    if (matcher.matches()) // 处理数字   
				     e.doit = true;   
				    else if (e.text.length() > 0) // 有字符情况,包含中文、空格   
				     e.doit = false;   
				    else  
				     // 控制键   
				     e.doit = true;   
				   }   
				  });
//		device_combo = new CCombo(mini_composite, SWT.BORDER | SWT.READ_ONLY | SWT.SIMPLE);
//		device_combo.setBounds(263, 50, 61, 23);
//		device_combo.setItems(device_type);
//		device_combo.select(0);
		conn_btn = new Button(mini_composite, SWT.NONE);
		tc.setConnBtn(conn_btn);
		conn_btn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				
				if("连接".equals(conn_btn.getText())){
					if("".equals(dsp_ip_text.getText()) || "".equals(dsp_port_text.getText())){
						MessageBox msgBox = new MessageBox( shell, SWT.OK | SWT.ICON_INFORMATION );
					    msgBox.setText( "连接失败!" );
					    msgBox.setMessage( "ip和端口为必填项!" );
					    msgBox.open();
						return;
					}else{
						boolean checkDevicePort=checkDeviceTypeAndPort(shell);
						
						if(checkDevicePort){//判断设备类型与连接的端口
							String ip=dsp_ip_text.getText();
							int port=Integer.valueOf(dsp_port_text.getText());
							String tmp_ip=ip.substring(0, 6);
							
							if("172.16".equals(tmp_ip)){//限定只能连接到非生产dsp服务器
								if(tc.conn(ip,port)){
									tc.getSr().setBa(ba);
									log_info_text.append("服务器已连接\n");
									connectFlag=true;
									dsp_ip_text.setEnabled(false);
									dsp_port_text.setEnabled(false);
									conn_btn.setText("断开");
									imei_text.setEnabled(false);
									//device_combo.setEnabled(false);
									device_type_text.setText(deviceTypeTextVisible(device_type_int));
									return;
								}else{
									MessageBox msgBox = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR );
								    msgBox.setText( "连接失败!" );
								    msgBox.setMessage( "服务器连接失败,请检查IP、端口是否正确及服务端端口是否开启!" );
								    msgBox.open();
								    return;
								}
							}else{
								for(int i=0;i<allowDeviceList.length;i++){
									if(imei_text.getText().equals(allowDeviceList[i])){
										allowDeviceConnect=true;
										break;
									}
								}
								if(allowDeviceConnect){//判断设备是否在连到生产环境的设备列表里
									if(tc.conn(ip,port)){
										tc.getSr().setBa(ba);
										log_info_text.append("服务器已连接\n");
										connectFlag=true;
										dsp_ip_text.setEnabled(false);
										dsp_port_text.setEnabled(false);
										conn_btn.setText("断开");
										imei_text.setEnabled(false);
										//device_combo.setEnabled(false);
										device_type_text.setText(deviceTypeTextVisible(device_type_int));
										return;
									}else{
										MessageBox msgBox = new MessageBox( shell, SWT.OK | SWT.ICON_ERROR );
									    msgBox.setText( "连接失败!" );
									    msgBox.setMessage( "服务器连接失败,请检查IP、端口是否正确及服务端端口是否开启!" );
									    msgBox.open();
									    return;
									}
								}else{
									MessageBox msgBox = new MessageBox( shell, SWT.OK | SWT.ICON_ERROR );
									msgBox.setText( "连接失败!" );
									msgBox.setMessage( "服务器连接失败,您的设备不允许往指定环境模拟发送报文" );
									msgBox.open();
									return;
								}
							}
						}/*else{
							MessageBox msgBox = new MessageBox( shell, SWT.OK | SWT.ICON_INFORMATION );
							msgBox.setText( "连接失败!" );
							msgBox.setMessage( "该地址、端口不适合当前设备连接!!!请咨询DSP同事" );
							msgBox.open();
							return;
						}*/
					}
				}
				if("断开".equals(conn_btn.getText())){
					tc.close();
					if(null!=tc.iteratorSendAction)
						tc.iteratorSendAction.destroyThread=true;
					send_iteration_btn.setText("连续发");
					log_info_text.append("服务器已断开\n");
					conn_btn.setText("连接");
					ba.setSendString("stop");
					if(cb.count>0){
						send_stop_btn.setText("继续");
					}
					if(cb.count<=0){
						imei_text.setEnabled(true);
//						device_combo.setEnabled(true);
						device_type_text.setText(deviceTypeTextVisible(-1));
					}
					dsp_ip_text.setEnabled(true);
					dsp_port_text.setEnabled(true);
					
					connectFlag=false;
					
				}
				
				if("重新连接".equals(conn_btn.getText())){
					String ip=dsp_ip_text.getText();
					int port=Integer.valueOf(dsp_port_text.getText());
					if(tc.reconn(ip,port)){
						if(null!=dataList){
	            			if(cb.count>0)
	                			send_stop_btn.setText("继续");
	            		}
						log_info_text.append("服务器已连接\n");
						connectFlag=true;
						conn_btn.setText("断开");
					}else{
						reconnect_count++;
						connectFlag=false;
						MessageBox msgBox = new MessageBox( shell, SWT.OK | SWT.ICON_ERROR );
					    msgBox.setText( "连接失败!" );
					    msgBox.setMessage( "服务器重连失败,请检查IP、端口是否正确及服务端端口是否开启!" );
					    msgBox.open();
					    if(3==reconnect_count){
					    	dsp_ip_text.setEnabled(true);
							dsp_port_text.setEnabled(true);
					    	conn_btn.setText("连接");
					    	reconnect_count=0;
					    }
					}
				}
				
			}
		});
		conn_btn.setBounds(306, 20, 61, 27);
		conn_btn.setText("连接");
		
		Group group = new Group(mini_composite, SWT.NONE);
		group.setText("自定义");
		group.setBounds(10, 94, 357, 236);
		
		Label lng_lbl = new Label(group, SWT.NONE);
		lng_lbl.setBounds(10, 28, 36, 17);
		lng_lbl.setText("经度：");
		
		Label lat_lbl = new Label(group, SWT.NONE);
		lat_lbl.setBounds(10, 63, 36, 17);
		lat_lbl.setText("纬度：");
		
		lng_text = new Text(group, SWT.BORDER);
		lng_text.setBounds(52, 25, 87, 23);
		lng_text.setTextLimit(11);
		lng_text.addVerifyListener(new LngLatVerifyListener());
		lat_text = new Text(group, SWT.BORDER);
		lat_text.setBounds(52, 60, 87, 23);
		lat_text.setTextLimit(11);
		lat_text.addVerifyListener(new LngLatVerifyListener());
		Label speed_lbl = new Label(group, SWT.NONE);
		speed_lbl.setBounds(162, 28, 42, 17);
		speed_lbl.setText("速度：");
		
		Label course_lbl = new Label(group, SWT.NONE);
		course_lbl.setBounds(162, 63, 42, 17);
		course_lbl.setText("方向：");
		
		speed_text = new Text(group, SWT.BORDER);
		speed_text.setBounds(204, 25, 36, 23);
		speed_text.setTextLimit(3);
		speed_text.addVerifyListener(new VerifyListener() {   
		   public void verifyText(VerifyEvent e) {   
		    // 几种情况，输入控制键，输入中文，输入字符，输入数字   
		    // 正整数验证   
		    Pattern pattern = Pattern.compile("[0-9]\\d*");   
		    Matcher matcher = pattern.matcher(e.text);   
		    if (matcher.matches()) // 处理数字   
		     e.doit = true;   
		    else if (e.text.length() > 0) // 有字符情况,包含中文、空格   
		     e.doit = false;   
		    else  
		     // 控制键   
		     e.doit = true;   
		   }   
		  });  
		
		course_text = new Text(group, SWT.BORDER);
		course_text.setBounds(204, 60, 36, 23);
		course_text.setTextLimit(3);
		course_text.addVerifyListener(new VerifyListener() {   
		   public void verifyText(VerifyEvent e) {   
		    // 几种情况，输入控制键，输入中文，输入字符，输入数字   
		    // 正整数验证   
		    Pattern pattern = Pattern.compile("[0-9]\\d*");   
		    Matcher matcher = pattern.matcher(e.text);   
		    if (matcher.matches()) // 处理数字   
		     e.doit = true;   
		    else if (e.text.length() > 0) // 有字符情况,包含中文、空格   
		     e.doit = false;   
		    else  
		     // 控制键   
		     e.doit = true;   
		   }   
		  });  
		
		Label gpstime_lbl = new Label(group, SWT.NONE);
		gpstime_lbl.setBounds(10, 102, 61, 17);
		gpstime_lbl.setText("GPS时间：");
		
		Group group_1 = new Group(group, SWT.NONE);
		group_1.setBounds(75, 86, 167, 40);
		
		Date currentTime = new Date();
	 	msgsendtime = new SimpleDateFormat("yy MM dd HH mm ss");
	 	nowtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	 	msgsendtime.format(currentTime);
	 	displaytime = nowtime.format(currentTime);
		
		displaytime_text = new Text(group_1, SWT.NONE);
		displaytime_text.setBounds(4, 15, 122, 18);
		displaytime_text.setText(displaytime);
		settime_btn = new Button(group_1, SWT.NONE);
		settime_btn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
	   		 	
				final Shell dialog = new Shell(shell, SWT.DIALOG_TRIM);
	               dialog.setLayout(new GridLayout(3 , false ));
	                final DateTime calendar = new DateTime(dialog, SWT.CALENDAR | SWT.BORDER);
	                final DateTime time = new DateTime(dialog, SWT.TIME);
	                new Label(dialog, SWT.NONE);
	                new Label(dialog, SWT.NONE);
	               Button ok = new Button(dialog, SWT.PUSH);
	               ok.setText("OK");
	               ok.setLayoutData( new  GridData(SWT.FILL, SWT.CENTER,  false ,  false ));
	               ok.addSelectionListener( new  SelectionAdapter()  {
	                    public   void  widgetSelected(SelectionEvent e)  {
	                    	String year=String.valueOf(calendar.getYear());
	                    	String month=String.valueOf(calendar.getMonth()+1);
	                    	String day=String.valueOf(calendar.getDay());
	                    	String hour=String.valueOf(time.getHours());
	                    	String minutes=String.valueOf(time.getMinutes());
	                    	String seconds=String.valueOf(time.getSeconds());
	                    	if(month.length()<2)
	                    		month="0"+month;
	                    	if(day.length()<2)
	                    		day="0"+day;
	                    	if(hour.length()<2)
	                    		hour="0"+hour;
	                    	if(minutes.length()<2)
	                    		minutes="0"+minutes;
	                    	if(seconds.length()<2)
	                    		seconds="0"+seconds;
	                       String selectTime=year+"-"+month+"-"+day+" "+hour+":"+minutes+":"+seconds;
	                       displaytime_text.setText(selectTime);
	                       dialog.close();
	                   } 
	               } );
	               dialog.setDefaultButton(ok);
	               dialog.pack();
	               dialog.open();
			}
		});
		settime_btn.setBounds(128, 10, 36, 27);
		settime_btn.setText("选择");
		
		final Button send_this_btn = new Button(group, SWT.NONE);
		send_this_btn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if(connectFlag){
					tc.send("this","","",device_type_int,imei_text.getText(),acc_status,displaytime_text.getText(),lng_text.getText(),lat_text.getText(),speed_text.getText(),course_text.getText());
				}else{
					MessageBox msgBox = new MessageBox( shell, SWT.OK | SWT.ICON_INFORMATION );
				    msgBox.setText( "发送失败!" );
				    msgBox.setMessage( "服务器未连接!" );
				    msgBox.open();
				}
				
			}
		});
		send_this_btn.setBounds(286, 97, 61, 27);
		send_this_btn.setText("发这条");
		
		send_totaltime_spinner = new Spinner(group, SWT.BORDER);
		send_totaltime_spinner.setBounds(45, 145, 54, 23);
		send_totaltime_spinner.setMinimum(1);
		
		send_iteration_btn = new Button(group, SWT.NONE);
		tc.setSend_Iteration_Btn(send_iteration_btn);
		send_iteration_btn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if("连续发".equals(send_iteration_btn.getText())){
					if(connectFlag){
						MessageBox sendselect = new MessageBox( shell, SWT.OK | SWT.CANCEL |SWT.ICON_QUESTION );
						sendselect.setText( "请注意!" );
						sendselect.setMessage( "连续发送将以当前时间每间隔"+send_iterationtime_spinner.getText()+"秒持续发送自定义内容"+send_totaltime_spinner.getText()+"分钟!\nGPS时间设置无效" );
						if (sendselect.open() == SWT.OK){
							log_info_text.append("连续发送开始\n");
							tc.send("",send_totaltime_spinner.getText(),send_iterationtime_spinner.getText(),device_type_int,imei_text.getText(),acc_status,displaytime_text.getText(),lng_text.getText(),lat_text.getText(),speed_text.getText(),course_text.getText());
							send_iteration_btn.setText("取消");
							acc_status_btn.setText("熄火");
							return;
						}
					}else{
						MessageBox msgBox = new MessageBox( shell, SWT.OK | SWT.ICON_INFORMATION );
					    msgBox.setText( "发送失败!" );
					    msgBox.setMessage( "服务器未连接!" );
					    msgBox.open();
					}
					
				}
				if("取消".equals(send_iteration_btn.getText())){
					tc.iteratorSendAction.destroyThread=true;
					send_iteration_btn.setText("连续发");
					log_info_text.append("连续发送结束\n");
				}
				
			}
		});
		send_iteration_btn.setBounds(286, 143, 61, 27);
		send_iteration_btn.setText("连续发");
		
		Label send_totaltime_lbl = new Label(group, SWT.NONE);
		send_totaltime_lbl.setFont(SWTResourceManager.getFont("微软雅黑", 9, SWT.NORMAL));
		send_totaltime_lbl.setBounds(10, 148, 36, 17);
		send_totaltime_lbl.setText("持续：");
		
		Label send_totaltime_unit_lbl = new Label(group, SWT.NONE);
		send_totaltime_unit_lbl.setText("分");
		send_totaltime_unit_lbl.setFont(SWTResourceManager.getFont("微软雅黑", 9, SWT.NORMAL));
		send_totaltime_unit_lbl.setBounds(101, 148, 29, 17);
		
		Label send_iterationtime_lbl = new Label(group, SWT.NONE);
		send_iterationtime_lbl.setText("发送间隔：");
		send_iterationtime_lbl.setFont(SWTResourceManager.getFont("微软雅黑", 9, SWT.NORMAL));
		send_iterationtime_lbl.setBounds(143, 148, 61, 17);
		
		send_iterationtime_spinner = new Spinner(group, SWT.BORDER);
		send_iterationtime_spinner.setBounds(204, 145, 38, 23);
		send_iterationtime_spinner.setMaximum(60);
		send_iterationtime_spinner.setMinimum(2);
		send_iterationtime_spinner.setIncrement(1);
		Label send_iterationtime_unit_lbl = new Label(group, SWT.NONE);
		send_iterationtime_unit_lbl.setText("秒");
		send_iterationtime_unit_lbl.setFont(SWTResourceManager.getFont("微软雅黑", 9, SWT.NORMAL));
		send_iterationtime_unit_lbl.setBounds(243, 148, 18, 17);
		
		Label acc_statuc_lbl = new Label(group, SWT.NONE);
		acc_statuc_lbl.setText("ACC：");
		acc_statuc_lbl.setBounds(257, 28, 36, 17);
		
		final Button custom_send_btn = new Button(group, SWT.NONE);
		custom_send_btn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if(connectFlag){
					InputDialog inputDialog = new InputDialog(shell,"构造报文","例：7E 80 01 00 05 01 50 90 00 00 24 09 C5 09 C3 05 00 00 62 7E","",null);    
					if(inputDialog.open() == InputDialog.OK){ 
					     String customMsg = inputDialog.getValue();    
					     if(customMsg.length()==0){
					    	 MessageBox msgBox = new MessageBox( shell, SWT.OK | SWT.ICON_INFORMATION );
						     msgBox.setText( "发送失败!" );
						     msgBox.setMessage( "发送内容不能为空!" );
						     msgBox.open();
					     }else{
					    	 tc.customSend(customMsg);
					     }
					} 
				}else{
					MessageBox msgBox = new MessageBox( shell, SWT.OK | SWT.ICON_INFORMATION );
				    msgBox.setText( "发送失败!" );
				    msgBox.setMessage( "服务器未连接!" );
				    msgBox.open();
				}
			}
		});
		custom_send_btn.setBounds(267, 58, 80, 27);
		custom_send_btn.setText("自编发送");
		
		acc_status_btn = new Button(group, SWT.NONE);
		tc.setAcc_Status_Btn(acc_status_btn);
		ba.setAcc_Status_Btn(acc_status_btn);
		acc_status_btn.setBounds(297, 23, 50, 27);
		acc_status_btn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if("点火".equals(acc_status_btn.getText())){
					acc_status_btn.setText("熄火");
					acc_status=0;
					as.setStatus(0);
					return;
				}
				
				if("熄火".equals(acc_status_btn.getText())){
					acc_status_btn.setText("点火");
					acc_status=1;
					as.setStatus(1);
					return;
				}
				
			}
		});
		acc_status_btn.setText("点火");
		
		Label event_type_lbl = new Label(group, SWT.NONE);
		event_type_lbl.setBounds(10, 195, 61, 17);
		event_type_lbl.setText("事件类型：");
		
		Button btnNewButton = new Button(group, SWT.NONE);
		btnNewButton.setBounds(267, 192, 80, 27);
		btnNewButton.setText("事件发送");
		
		CCombo event_type_combo = new CCombo(group, SWT.BORDER | SWT.READ_ONLY | SWT.SIMPLE);
		event_type_combo.setBounds(73, 193, 87, 23);
		event_type_combo.setItems(event_type);
		event_type_combo.select(0);
		Label import_lbl = new Label(mini_composite, SWT.NONE);
		import_lbl.setBounds(21, 345, 61, 17);
		import_lbl.setText("导入CSV：");
		
		Label send_interval = new Label(mini_composite, SWT.NONE);
		send_interval.setBounds(21, 381, 107, 17);
		send_interval.setText("导入文件发送间隔：");
		
		import_path_text = new Text(mini_composite, SWT.BORDER);
		import_path_text.setBounds(83, 342, 217, 23);
		
		final Button open_path_btn = new Button(mini_composite, SWT.NONE);
		ba.setOpenPathBtn(open_path_btn);
		open_path_btn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				 
				//新建文件对话框，并设置为打开的方式
				FileDialog filedlg=new FileDialog(shell,SWT.OPEN);
				filedlg.setText("文件选择");
				//设置初始路径
				filedlg.setFilterPath("SystemRoot");
				//设置所打开文件的扩展名  
				filedlg.setFilterExtensions(new String[] {"*.csv"});  
			    //设置显示到下拉框中的扩展名的名称  
				filedlg.setFilterNames( new String[]{"Text Files (*.csv)"});  
				
				//打开文件对话框，返回选中文件的绝对路径
				String selected=filedlg.open();
				
				if(null!=selected){
					import_path_text.setText(selected);
					tracePath=selected;
					
					//表格里显示导入的CSV数据
					String path=tracePath.replaceAll("\\\\", "/");
					try {
			            BufferedReader reader = new BufferedReader(new FileReader(path));
			            reader.readLine();//第一行信息，为标题信息，不用，如果需要，注释掉
			            String[] data=null;
						String line = null;
						
						if(dataList.size()>0){
							dataList.clear();
							send_btn.setEnabled(true);
							log_info_text.setText("");
			            }
						if(opencount>0){
							csv_table.removeAll();
							send_btn.setEnabled(true);
							//ba.destroyThread=false;
							send_btn.setText("发送");
						}
			            	
			            while((line=reader.readLine())!=null){
			                String item[] = line.split("，");
			                 
			                String last = item[item.length-1];
			                //int value = Integer.parseInt(last);//如果是数值，可以转化为数值
			                data=last.split(",");
			                TableItem ti=new TableItem(csv_table,SWT.LEFT);
			                ti.setText(new String[]{data[0],data[1],data[2],data[3]});
			                dataList.add(last);
			            }
			           
			        } catch (Exception e1) {
			            e1.printStackTrace(); 
			        }
					ba.setImportCsvList(dataList);
//					ba.setDeviceCombo(device_combo);
					ba.setCourseText(course_text);
					ba.setDisplaytimeText(displaytime_text);
					ba.setImeiText(imei_text);
					ba.setLatText(lat_text);
					ba.setLngText(lng_text);
					ba.setSpeedText(speed_text);
					ba.setSendtotaltimeSpinner(send_totaltime_spinner);
					ba.setSenditerationtimeSpinner(send_iterationtime_spinner);
					ba.setSendthisBtn(send_this_btn);
					ba.setSenditerationBtn(send_iteration_btn);
					ba.setSettimeBtn(settime_btn);
					ba.setCustom_Send_Btn(custom_send_btn);
					
					lng_text.setEnabled(false);
					lat_text.setEnabled(false);
					speed_text.setEnabled(false);
					course_text.setEnabled(false);
					displaytime_text.setEnabled(false);
					send_totaltime_spinner.setEnabled(false);
					send_iterationtime_spinner.setEnabled(false);
					send_this_btn.setEnabled(false);
					send_iteration_btn.setEnabled(false);
					settime_btn.setEnabled(false);
					custom_send_btn.setEnabled(false);
					opencount++;
				}
				
			}
		});
		open_path_btn.setBounds(306, 340, 61, 27);
		open_path_btn.setText("打开");
		
		send_interval_spinner = new Spinner(mini_composite, SWT.BORDER);
		send_interval_spinner.setBounds(134, 380, 40, 23);
		send_interval_spinner.setMaximum(60);
		send_interval_spinner.setMinimum(2);
		send_interval_spinner.setIncrement(1);
		ba.setSend_Interval_Spinner(send_interval_spinner);
		send_btn = new Button(mini_composite, SWT.NONE);
		ba.setSendBtn(send_btn);
		send_btn.addSelectionListener(new SelectionAdapter() {
			@SuppressWarnings("deprecation")
			@Override
			public void widgetSelected(SelectionEvent e) {
				if("发送".equals(send_btn.getText())){
					if(connectFlag){
						List l=ch.getRouteList();
						if(dataList.size()>0){
							ba.setLog_Info_Text(log_info_text);
							ba.setSend(true);
							actionThread=new Thread(ba);
							ba.setSendString("continue");
							ba.setDeviceType(device_type_int);
							actionThread.start();
							//根据连接dsp传入相应环境的 dsp api地址
							if("172.16.1.44".equals(dsp_ip_text.getText()) || "172.30.2.188".equals(dsp_ip_text.getText()) || "172.30.2.234".equals(dsp_ip_text.getText()) || "172.30.3.191".equals(dsp_ip_text.getText()) || "172.30.3.33".equals(dsp_ip_text.getText()) || "172.30.5.243".equals(dsp_ip_text.getText()) || "172.30.5.250".equals(dsp_ip_text.getText())){
								ba.setDspInterface(new CallDspInterfaceAction(testDspApi,shell,ba));
							}else if("172.16.1.45".equals(dsp_ip_text.getText()) || "172.16.1.215".equals(dsp_ip_text.getText()) || "172.16.1.4".equals(dsp_ip_text.getText()) || "172.16.1.216".equals(dsp_ip_text.getText()) || "172.16.1.5".equals(dsp_ip_text.getText())  || "172.16.1.217".equals(dsp_ip_text.getText())  || "172.16.1.6".equals(dsp_ip_text.getText())){
								ba.setDspInterface(new CallDspInterfaceAction(demoDspApi,shell,ba));
							}else{
								ba.setDspInterface(new CallDspInterfaceAction(productDspApi,shell,ba));
							}
							send_stop_btn.setEnabled(true);
							open_path_btn.setEnabled(false);
							send_interval_spinner.setEnabled(false);
							ba.setSend_Interval_Time(Integer.valueOf(send_interval_spinner.getText()));
							send_stop_btn.setText("停止");
							acc_status_btn.setText("熄火");
							as.setStatus(0);
						}else if(l.size()>0){
							String htmlPath=Thread.currentThread().getContextClassLoader().getResource("res/location.html").getPath();
							System.out.println(htmlPath);
//							browser.setUrl(htmlPath.substring(6,htmlPath.indexOf("sendtrace"))+"location.html");
							browser.setUrl(htmlPath.substring(1,htmlPath.length()));
						    
						    ba.setBrowser(browser);
							ba.setImeiText(imei_text);
							ba.setRouteList(l);
							ba.setLog_Info_Text(log_info_text);
							ba.setSend(true);
							actionThread=new Thread(ba);
							ba.setSendString("continue");
							ba.setDeviceType(device_type_int);
							actionThread.start();
							//根据连接dsp传入相应环境的 dsp api地址
							if("172.16.1.44".equals(dsp_ip_text.getText()) || "172.30.2.188".equals(dsp_ip_text.getText()) || "172.30.2.234".equals(dsp_ip_text.getText()) || "172.30.3.191".equals(dsp_ip_text.getText()) || "172.30.3.33".equals(dsp_ip_text.getText()) || "172.30.5.243".equals(dsp_ip_text.getText()) || "172.30.5.250".equals(dsp_ip_text.getText())){
								ba.setDspInterface(new CallDspInterfaceAction(testDspApi,shell,ba));
							}else if("172.16.1.45".equals(dsp_ip_text.getText()) || "172.16.1.215".equals(dsp_ip_text.getText()) || "172.16.1.4".equals(dsp_ip_text.getText()) || "172.16.1.216".equals(dsp_ip_text.getText()) || "172.16.1.5".equals(dsp_ip_text.getText())  || "172.16.1.217".equals(dsp_ip_text.getText())  || "172.16.1.6".equals(dsp_ip_text.getText())){
								ba.setDspInterface(new CallDspInterfaceAction(demoDspApi,shell,ba));
							}else{
								ba.setDspInterface(new CallDspInterfaceAction(productDspApi,shell,ba));
							}
							send_stop_btn.setEnabled(true);
							open_path_btn.setEnabled(false);
							send_interval_spinner.setEnabled(false);
							ba.setSend_Interval_Time(Integer.valueOf(send_interval_spinner.getText()));
							send_stop_btn.setText("停止");
							acc_status_btn.setText("熄火");
							as.setStatus(0);
						}else{
							MessageBox msgBox = new MessageBox( shell, SWT.OK | SWT.ICON_INFORMATION );
						    msgBox.setText( "发送失败!" );
						    msgBox.setMessage( "数据未导入!" );
						    msgBox.open();
						}
						
					}else{
						MessageBox msgBox = new MessageBox( shell, SWT.OK | SWT.ICON_INFORMATION );
					    msgBox.setText( "发送失败!" );
					    msgBox.setMessage( "服务器未连接!" );
					    msgBox.open();
					}
					if("continue".equals(ba.getSendString()))
						send_btn.setText("终止");
				}
				if("终止".equals(send_btn.getText()) && cb.count>0){
					actionThread.stop();
					csv_table.removeAll();
					dataList.clear();
					l.clear();
					cb.count=0;
					send_btn.setText("发送");
					send_stop_btn.setEnabled(false);
					open_path_btn.setEnabled(true);
					ba.setSendString("stop");
					log_info_text.append("发送已终止\n");
					send_interval_spinner.setEnabled(true);
					
					lng_text.setEnabled(true);
					lat_text.setEnabled(true);
					speed_text.setEnabled(true);
					course_text.setEnabled(true);
					displaytime_text.setEnabled(true);
					send_totaltime_spinner.setEnabled(true);
					send_iterationtime_spinner.setEnabled(true);
					send_this_btn.setEnabled(true);
					send_iteration_btn.setEnabled(true);
					settime_btn.setEnabled(true);
					custom_send_btn.setEnabled(true);
					import_path_text.setText("");
					
				}
				
			}
		});
		send_btn.setBounds(306, 376, 61, 27);
		send_btn.setText("发送");
		
		Label import_csv_table_lbl = new Label(mini_composite, SWT.NONE);
		import_csv_table_lbl.setBounds(396, 10, 61, 17);
		import_csv_table_lbl.setText("CSV数据：");
		
		Label log_info_lbl = new Label(mini_composite, SWT.NONE);
		log_info_lbl.setBounds(397, 244, 88, 17);
		log_info_lbl.setText("发送应答日志：");
		
		Button clear_log_info_btn = new Button(mini_composite, SWT.NONE);
		clear_log_info_btn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				log_info_text.setText("");
			}
		});
		clear_log_info_btn.setBounds(590, 239, 80, 27);
		clear_log_info_btn.setText("清除日志");
		
		csv_table = new Table(mini_composite, SWT.BORDER | SWT.FULL_SELECTION);
		csv_table.setBounds(396, 33, 274, 192);
		csv_table.setHeaderVisible(true);
		csv_table.setLinesVisible(true);
		ba.setCscTable(csv_table);
		TableColumn tblclmnNewColumn = new TableColumn(csv_table, SWT.NONE);
		tblclmnNewColumn.setWidth(72);
		tblclmnNewColumn.setText("纬度");
		
		TableColumn tblclmnNewColumn_1 = new TableColumn(csv_table, SWT.NONE);
		tblclmnNewColumn_1.setWidth(81);
		tblclmnNewColumn_1.setText("经度");
		
		TableColumn tblclmnNewColumn_2 = new TableColumn(csv_table, SWT.NONE);
		tblclmnNewColumn_2.setWidth(43);
		tblclmnNewColumn_2.setText("速度");
		
		TableColumn tblclmnNewColumn_3 = new TableColumn(csv_table, SWT.NONE);
		tblclmnNewColumn_3.setWidth(50);
		tblclmnNewColumn_3.setText("方向");
		
		send_stop_btn = new Button(mini_composite, SWT.NONE);
		send_stop_btn.setEnabled(false);
		ba.setStopBtn(send_stop_btn);
		tc.setSend_Stop_Btn(send_stop_btn);
		
		send_stop_btn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if("停止".equals(send_stop_btn.getText())){
					ba.setSendString("stop");
					if(cb.count>0)
						send_stop_btn.setText("继续");
					
					return;
				}
				if("继续".equals(send_stop_btn.getText())){
					if(connectFlag){
						ba.setSendString("continue");
						send_stop_btn.setText("停止");
					}else{
						MessageBox msgBox = new MessageBox( shell, SWT.OK | SWT.ICON_INFORMATION );
					    msgBox.setText( "发送失败!" );
					    msgBox.setMessage( "服务器未连接!" );
					    msgBox.open();
					}
				}
			}
		});
		send_stop_btn.setBounds(237, 376, 61, 27);
		send_stop_btn.setText("停止");
		
		
		Label device_type_lbl = new Label(mini_composite, SWT.NONE);
		device_type_lbl.setBounds(196, 68, 61, 17);
		device_type_lbl.setText("设备类型：");
		
		Label imei_lbl = new Label(mini_composite, SWT.NONE);
		imei_lbl.setBounds(18, 68, 42, 17);
		imei_lbl.setText("IMEI：");
		
		
		
		Label send_interval_lbl = new Label(mini_composite, SWT.NONE);
		send_interval_lbl.setText("秒");
		send_interval_lbl.setFont(SWTResourceManager.getFont("微软雅黑", 9, SWT.NORMAL));
		send_interval_lbl.setBounds(173, 381, 18, 17);
		
		device_type_text = new Text(mini_composite, SWT.BORDER | SWT.READ_ONLY | SWT.CENTER);
		device_type_text.setBounds(260, 65, 51, 23);
		device_type_text.setText("NULL");
	    
		TabItem standard_tabItem = new TabItem(tabFolder, SWT.NONE);
		standard_tabItem.setText("详细报文");
		Composite standard_composite = new Composite(tabFolder, SWT.NONE);
		standard_composite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_BACKGROUND));
		standard_tabItem.setControl(standard_composite);
		shell.open();
		shell.layout();
//		while (!shell.isDisposed()) {
//			if (!display.readAndDispatch()) {
//				display.sleep();
//			}
//		}
//		System.exit(1);
	}
	
	
	/**
	 * Launch the application.
	 * @param args
	 */
	public static void main(String[] args) {
//	  new MessageSend();
	}
	
	public static String deviceTypeTextVisible(int type){
		String deviceType="NULL";
		if(type==0)
			deviceType="SMART";
		if(type==1)
			deviceType="部标";
		return deviceType;
	}
	
	public static boolean checkDeviceTypeAndPort(Shell shell){
		boolean checkDeviceTypeAndPort=false;
		String imeitype="";
		if(15==imei_text.getText().length()){
			imeitype=imei_text.getText().substring(0,4);
			
			if(imeitype.equals("1070")){
				for(int i=0;i<smartServerPortList.length;i++){
					if(dsp_port_text.getText().equals(smartServerPortList[i])){
						checkDeviceTypeAndPort=true;
						device_type_int=0;
					}
				}
			}else if(imeitype.equals("1060")){
				for(int i=0;i<gnnsServerPortList.length;i++){
					if(dsp_port_text.getText().equals(gnnsServerPortList[i])){
						checkDeviceTypeAndPort=true;
						device_type_int=1;
					}
				}
			}else{
				MessageBox msgBox = new MessageBox( shell, SWT.OK | SWT.ICON_INFORMATION );
				msgBox.setText( "连接失败!" );
				msgBox.setMessage( "该地址、端口不适合当前设备连接!!!请咨询DSP同事" );
				msgBox.open();
			}
		}else{
			MessageBox msgBox = new MessageBox( shell, SWT.OK | SWT.ICON_INFORMATION );
			msgBox.setText( "提示!" );
			msgBox.setMessage( "IMEI输入不正确!请到GSP系统查询" );
			msgBox.open();
		}
		return checkDeviceTypeAndPort;
	}
}
